﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using WMM.Tapioca.Linkbase;
using WMM.Tapioca.Instance;
using WMM.Tapioca.Taxonomy;

namespace WMM.Tapioca.Formula.Filters
{
    /// <summary>
    /// The sibling filter can be used to select facts that are siblings of an another fact. 
    /// </summary>
    public class SiblingFilter : Filter
    {
        private string variable;

        /// <returns> The @variable attribute on the sibling filter.  </returns>
        public string Variable
        {
            get { return variable; }
            set { variable = value; }
        }

        /// <summary>
        /// Constructor.
        /// </summary>
        public SiblingFilter(Resource resource)
            : base(resource)
        {
            string qname = (string)resource.ResourceXElement.Attribute("variable") ?? string.Empty;
            qname = qname.TrimEnd().TrimStart();
            qname = Regex.Replace(qname, @"\s+", " ");
            variable = qname;
        }


        public override List<FactItem> EvaluateFilter(VariableSet variableSet, List<FactItem> itemsToFilter, DTS dts)
        {
            this.dts = dts;

            List<FactItem> itemListTemp = new List<FactItem>();

            foreach (FactItem itemToFilter in itemsToFilter)
            {
                FactVariable factVariable = GetFactVariable(Variable, variableSet);

                List<FactItem> inputFacts = GetItems(dts.Instance.Facts);

                List<FactItem> factItems = variableSet.FilteringFacts(variableSet, factVariable, inputFacts);

                for (int i = 0; i < factItems.Count; i++)
                {
                    if (Complement ? !itemToFilter.FactElement.Parent.Equals(factItems[i].FactElement.Parent) : itemToFilter.FactElement.Parent.Equals(factItems[i].FactElement.Parent))
                    {
                        itemListTemp.Add(itemToFilter);
                        break;
                    }
                }
            }

            return itemListTemp;
        }
    }
}
